package com.rockcent.mall.lib.repository;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rockcent.common.common.SQLListDoing;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.mall.lib.domain.enumclass.PacketCouponStatus;
import com.rockcent.mall.lib.dto.RedPacketCouponDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by ISSUSER on 2016/11/11 0011.
 */
@Repository
public class RedPacketCouponRepositoryImpl implements RedPacketCouponRepositoryCustom {

    private Logger log = LoggerFactory.getLogger(RedPacketCouponRepositoryImpl.class);
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public List<RedPacketCouponDto> findAllByRedPacketIdAndIsShareRewardAndStatus
            (Long redPacketId, Whether isShareReward, PacketCouponStatus status) {
        SQLListDoing<RedPacketCouponDto> doing = (sql, fields, params, typeReferenceMap) -> {
            sql.append("select %s FROM red_packet_item t LEFT JOIN red_packet_coupon p ON " +
                    "p.red_packet_item_id=t.id WHERE p.red_packet_id=1 AND p.is_share_reward='NO'");
            if (null != status) {
                sql.append(" AND p.`status` = :status");
                params.put("status", status.toString());
            }
            sql.append(" ORDER BY p.last_updated DESC");
            fields.append("t.*,p.coupon_name,p.customer_head_url,p.last_updated AS last_updated,p.date_created AS date_created");
        };
        return doing.go(RedPacketCouponDto.class, jdbcTemplate, log, objectMapper);
    }
}
